package com.market.sys.api.client;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.market.sys.common.Result;
import com.market.sys.entity.Booth;
import com.market.sys.entity.Contract;
import com.market.sys.entity.User;
import com.market.sys.entity.UserCollection;
import com.market.sys.mapper.BoothMapper;
import com.market.sys.mapper.UserCollectionMapper;
import com.market.sys.service.IBoothService;
import com.market.sys.service.IContractService;
import com.market.sys.service.IUserService;
import com.market.sys.util.Constants;
import com.market.sys.util.EmptyUtil;
import com.market.sys.util.TimeUtil;
import com.market.sys.vo.BoothVO;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xd
 * @since 2024-03-26
 */
@RestController
@RequestMapping("/sys/booth")
public class BoothController {

    @Resource
    private IBoothService boothService;

    @Resource
    private IUserService userService;

    @Resource
    private IContractService contractService;

    @Resource
    private BoothMapper boothMapper;

    @Resource
    private UserCollectionMapper userCollectionMapper;

    @PostMapping("/add")
    public Result<?> add(@RequestBody Map<String, Object> paramsMap) {
        Booth booth = BeanUtil.fillBeanWithMap(paramsMap, new Booth(), false);
        booth.setCreateTime(TimeUtil.timeYmdhms(new Date()));
        booth.setState(0);
        if (boothService.save(booth)) {
            return Result.success("上传成功，正在审核中");
        } else {
            return Result.error("上传失败");
        }
    }

    @PostMapping("/update")
    public Result<?> update(@RequestBody Map<String, Object> paramsMap) {
        Booth booth = BeanUtil.fillBeanWithMap(paramsMap, new Booth(), false);
        Booth one = boothService.query().eq("id", booth.getId()).one();
        if (one.getState() == 2){
            return Result.error("该摊位正在履行合同中，暂时无法修改");
        }
        if (boothService.updateById(booth)) {
            return Result.success("更新成功");
        } else {
            return Result.error("更新失败");
        }
    }

    @PostMapping("/delete")
    public Result<?> delete(@RequestBody Map<String, Object> paramsMap) {
        Booth booth = BeanUtil.fillBeanWithMap(paramsMap, new Booth(), false);
        if (boothService.remove(new LambdaQueryWrapper<Booth>().eq(Booth::getId, booth.getId()))) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    @PostMapping("/fetchMyRent")
    public Result<?> fetchMyRent(@RequestBody Map<String, Object> paramsMap){
        List<Contract> contractList = contractService.query().eq("b_id", String.valueOf(paramsMap.get("userId"))).list();
        List<Booth> boothList = new ArrayList<>();
        for (Contract contract : contractList) {
            Booth booth = boothService.query().eq("id", contract.getBoothId()).one();
            boothList.add(booth);
        }
        List<BoothVO> boothVOList = new ArrayList<>();
        for (Booth boo : boothList) {
            boothVOList.add(getBoothVO(boo));
        }

        return Result.success(boothVOList);
    }

    @PostMapping("/fetchById")
    public Result<?> fetchById(@RequestBody Map<String, Object> paramsMap){
        Booth booth = boothService.query().eq("id", paramsMap.get("id")).one();
        return Result.success(getBoothVO(booth));
    }

    @PostMapping("/fetchCollectList")
    public Result<?> fetchCollectList(@RequestBody Map<String,Object> conditionMap){
        LambdaQueryWrapper<UserCollection> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserCollection::getUserId,conditionMap.get("userId"))
                .eq(UserCollection::getType, conditionMap.get("type"))
                .orderByDesc(UserCollection::getCollectTime);
        List<UserCollection> userCollectionList = userCollectionMapper.selectList(lambdaQueryWrapper);
        List<BoothVO> boothVOList = new ArrayList<>();
        for (UserCollection userCollection : userCollectionList) {
            Booth booth = boothService.query().eq("id", userCollection.getThingId()).one();
            boothVOList.add(getBoothVO(booth));
        }
        return Result.success(boothVOList);
    }

    @PostMapping("/fetchBoothByCondition")
    public Result<?> fetchBoothByCondition(@RequestBody Map<String, Object> paramsMap){
        Page<Booth> page = new Page<>((int)paramsMap.get("pageNum"), (int)paramsMap.get("pageSize"));
        LambdaQueryWrapper<Booth> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Booth::getState, 1);
        if (!EmptyUtil.isStringEmpty((String) paramsMap.get("boothName"))){
            lambdaQueryWrapper.like(Booth::getBoothName, paramsMap.get("boothName"));
        }

        if (!EmptyUtil.isStringEmpty((String) paramsMap.get("location"))){
            String location = (String) paramsMap.get("location");
            lambdaQueryWrapper.like(Booth::getLocation, location);
        }

        if (!EmptyUtil.isStringEmpty((String) paramsMap.get("area"))){
            String area = (String) paramsMap.get("area");
            String[] areaSplit;
            if (area.contains("-")){
                areaSplit = area.split("-");
                lambdaQueryWrapper.between(Booth::getArea, areaSplit[0], areaSplit[1]);
            }else {
                lambdaQueryWrapper.gt(Booth::getArea, area);
            }
        }

        if (!EmptyUtil.isStringEmpty((String) paramsMap.get("sort"))){
            if ("slow".equals(paramsMap.get("sort"))){
                lambdaQueryWrapper.orderByAsc(Booth::getRentalFee);
            }
            if ("high".equals(paramsMap.get("sort"))){
                lambdaQueryWrapper.orderByDesc(Booth::getRentalFee);
            }
        }

        Page<Booth> boothPage = boothMapper.selectPage(page, lambdaQueryWrapper);
        List<BoothVO> boothVOList = new ArrayList<>();
        for (Booth boo : boothPage.getRecords()) {
            boothVOList.add(getBoothVO(boo));
        }

        return Result.success(boothVOList);
    }

    @PostMapping("/fetchBoothByUserId")
    public Result<?> fetchBoothByUserId(@RequestBody Map<String, Object> paramsMap) {
        Booth booth = BeanUtil.fillBeanWithMap(paramsMap, new Booth(), false);
        List<Booth> boothList = boothService.query()
                .eq("user_id", booth.getUserId()).orderByDesc("create_time").list();
        List<BoothVO> boothVOList = new ArrayList<>();
        for (Booth boo : boothList) {
            boothVOList.add(getBoothVO(boo));
        }

        return Result.success(boothVOList);
    }

    /**
     * 获取BoothVO
     * @param booth booth实体类
     * @return boothVO
     */
    private BoothVO getBoothVO(Booth booth){
        BoothVO boothVO = new BoothVO();
        BeanUtil.copyProperties(booth, boothVO, false);

        // 处理封面图片的逻辑
        // 将封面图片字符串按逗号分割成数组
        List<String> imgList = new ArrayList<>();
        if (!EmptyUtil.isStringEmpty(booth.getCoverImages())) {
            String[] imageArr = booth.getCoverImages().split(",");
            for (String img : imageArr) {
                // 添加下载链接前缀，并加入到图片链接列表中
                imgList.add(Constants.DOWNLOAD_URL + img);
            }
        }

        boothVO.setCoverImages(imgList);

        boothVO.setCreateTime(TimeUtil.completeGetTimeStamp(boothVO.getCreateTime()));

        User user = userService.query().eq("id",booth.getUserId()).one();
        boothVO.setNickName(user.getNickName());
        if (!EmptyUtil.isStringEmpty(user.getAvatar())){
            user.setAvatar(Constants.DOWNLOAD_URL + user.getAvatar());
        }
        boothVO.setAvatar(user.getAvatar());
        return boothVO;
    }
}
